/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tesam.gedeon.controller;

import com.tesam.gedeon.entity.Network;
import com.tesam.gedeon.entity.Region;
import com.tesam.gedeon.service.NetworkService;
import com.tesam.gedeon.service.RegionService;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.primefaces.json.JSONArray;
import org.primefaces.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author Sistema
 */
@Controller
public class RegionController {
    
    @Autowired
    SystemUserController system ;
    @Autowired
    RegionService regionService;
    @Autowired
    NetworkService networkService;
    
    Network network = new Network();
    
    @RequestMapping(value = "/mediationregion/index")
    public ModelAndView index(HttpServletRequest request){
        ModelAndView mv = new ModelAndView("/mediationregion/index");
        
        system.loadDataSystem(mv, request);
        
        return mv;
    }
    
      @RequestMapping(value = "/mediationregion/ajax" , method = RequestMethod.GET)
    public @ResponseBody
    String doAjaxGet() {

        int cantidadRegistros = 0;
        try { 
            List<Region> list = regionService.getListByLimit("name", "asc", cantidadRegistros, cantidadRegistros);
            // ArrayList<Cliente> list = clienteService.getAllClientes();
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();

            if (list.size() > 0) {
                for (Region region : list) {
                    JSONArray arrayPut = new JSONArray(); 
                    arrayPut.put(region.getCode()); 
                    arrayPut.put(region.getDescription());  
                    array.put(arrayPut);
                    // cantidadRegistros++;
                }
            }


            cantidadRegistros = regionService.getCountAll();
            json.put("iTotalRecords", cantidadRegistros);
            json.put("iTotalDisplayRecords", cantidadRegistros);
            json.put("aaData", array);

            return json.toString();
        } catch (Exception e) {
            System.out.print("Error - Controller-doAjax:" + e.getMessage());
        }

        return null;
    }
     
      @RequestMapping(value = "/mediationregion/ajax", method = RequestMethod.POST)
    public @ResponseBody
    String doAjaxPost(HttpServletRequest request) {

        List<Region> listRegion = null;
        int cantidadRegistros = 0;

        String[] columns = {"re.code", "re.description" ,"ne.description",  "re.description" };

        String startLimit = request.getParameter("iDisplayStart");
        String endLimit = request.getParameter("iDisplayLength");
        String dataToSort = columns[Integer.valueOf(request
                .getParameter("iSortCol_0"))];
        String directionOfOrder = request.getParameter("sSortDir_0");
        String textSearch = request.getParameter("sSearch").toUpperCase();
        System.out.println("ordernar por : "+dataToSort);
        int _startLimit = 0;
        int _endLimit = 0;

        if (startLimit != null && !startLimit.equals("0")) {

            if (!startLimit.trim().isEmpty()) {
                _startLimit = Integer.valueOf(startLimit);
            }
        }

        if (endLimit != null && !endLimit.equals("0")) {
            if (!endLimit.trim().isEmpty()) {
                _endLimit = Integer.valueOf(endLimit);
            }
        }

        if (textSearch != null) {
            if (!textSearch.trim().isEmpty()) {
                try{
                textSearch = textSearch.trim();
                Region region = new Region();
                region.setDescription(textSearch);
                
                listRegion = regionService.getSearchByName(dataToSort , directionOfOrder  ,_startLimit,_endLimit, region);
                cantidadRegistros = regionService.getCountBySearch(region);
                return regionService.getJsonDataFromArrayList(listRegion, cantidadRegistros);
                }catch(Exception e){
                System.out.println("controller : "+e.getMessage());
                }
                

            }
        }

        listRegion = regionService.getListByLimit(dataToSort, directionOfOrder ,_startLimit, _endLimit  );

        cantidadRegistros = regionService.getCountAll();

        return regionService.getJsonDataFromArrayList(listRegion, cantidadRegistros);
    }

    @RequestMapping(value = "/mediationregion/new" )
    public ModelAndView newRegion(HttpServletRequest request){
        ModelAndView mv = new ModelAndView("/mediationregion/new");
        
        system.loadDataSystem(mv, request);
        System.out.println("entro controller");
        mv.addObject("network", networkService.getListAll());
        
        return mv;
    }
    
    @RequestMapping(value = "/mediationregion/view")
    public ModelAndView view(@ModelAttribute("Region")Region region , HttpServletRequest request){
        ModelAndView mv = new ModelAndView("/mediationregion/view");
        
        system.loadDataSystem(mv, request);
        
        mv.addObject("region", regionService.getRegionById(region));
        
        return mv ;
    }
    
    @RequestMapping(value = "/mediationregion/newsave")
    public ModelAndView newSave(@ModelAttribute("Region")Region region , HttpServletRequest request){
        ModelAndView mv = new ModelAndView("/mediationregion/save");
        network.setId(Integer.parseInt(request.getParameter("CboNetwork")));
        
        region.setNetwork(network);
        
        mv.addObject("id", regionService.saveRegion(region));
          
        return mv;
    }
    
    @RequestMapping(value = "/mediationregion/delete")
    public ModelAndView delete(@ModelAttribute("Region")Region region , HttpServletRequest request){
        ModelAndView mv = new ModelAndView("/mediationregion/delete");
        
        regionService.delete(region);
          
        return mv;
    }
    
    @RequestMapping(value = "/mediationregion/update")
    public ModelAndView update(@ModelAttribute("Region")Region region , HttpServletRequest request){
        ModelAndView mv = new ModelAndView("/mediationregion/update");
        
        system.loadDataSystem(mv, request);
        
        mv.addObject("region", regionService.getRegionById(region));
        
        mv.addObject("network", networkService.getListAll());
        
        return mv;
    }
    
    @RequestMapping(value = "/mediationregion/saveupdate")
    public ModelAndView saveUpdate(@ModelAttribute("Region")Region region , HttpServletRequest request){
        ModelAndView mv = new ModelAndView("/mediationregion/view");
        
        system.loadDataSystem(mv, request);
        
        network.setId(Integer.parseInt(request.getParameter("CboNetwork")));
        
        region.setNetwork(network);
        
        mv.addObject("region", regionService.updateRegion(region));
        
        return mv ;
    }
    
}
